﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;

namespace BITS.PreCompiler.CSharp.Syntax.Extensions
{
    public static partial class CompilationExtension
    {
        public static Compilation WithUsings(this Compilation @this, IEnumerable<String> usings)
        {
            if (usings == null)
                return @this;

            return @this.WithOptions(@this.Options.WithUsings(usings));
        }

        public static Compilation WithOutputKind(this Compilation @this, OutputKind outputKind)
        {
            return @this.WithOptions(@this.Options.WithOutputKind(outputKind));
        }

        public static Assembly GetAssembly(this Compilation @this, Boolean @throw = true)
        {
            using (var output = new MemoryStream())
            {
                var emitResult = @this.Emit(output);

                if (emitResult.Success)
                    return Assembly.Load(output.ToArray());

                if (!@throw)
                    return null;

                var sb = new StringBuilder();

                foreach (var diagnostic in emitResult.Diagnostics)
                    sb.AppendLine(diagnostic.ToString());

                throw new ApplicationException(sb.ToString());
            }
        }
    }
}
